package fr.inserm.um915.bdibd.model;

import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;

public class ChromPosition
	implements Comparable<ChromPosition>
	{
	private byte chrom;
	private int position;
	
	public static class Binding extends TupleBinding<ChromPosition> 
		{
		@Override
		public void objectToEntry(ChromPosition o, TupleOutput out)
			{
			out.writeByte(o.chrom);
			out.writeInt(o.position);
			}
			
		@Override
		public ChromPosition entryToObject(TupleInput in)
			{
			byte s= in.readByte();
			int p=in.readInt();
			return new ChromPosition(s, p);
			}
		};
	
	public static final Binding	BINDING=new Binding();
	
	public ChromPosition(ChromPosition cp)
		{
		this.chrom=cp.chrom;
		this.position=cp.position;
		}

	
	public ChromPosition(String chrom,int position)
		{
		this.chrom=normalize(chrom);
		if(this.chrom<1) throw new IllegalArgumentException("bad chrom:"+chrom);
		this.position=position;
		}
	
	public ChromPosition(byte chrom,int position)
		{
		this.chrom=chrom;
		this.position=position;
		}
	
	static public byte normalize(String s)
		{
		s=s.toUpperCase().trim();
		if(s.startsWith("CHR")) s=s.substring(3);
		while(s.startsWith("0")) s=s.substring(1);
		if(s.equals("X")) return 23;
		if(s.equals("Y")) return 24;
		if(s.equals("M") || s.equals("MT")) return 25;
		int i=Integer.parseInt(s);
		if(i<1 || i>Byte.MAX_VALUE) return -1;
		return (byte)i;
		}
	
	static public String denormalize(byte b)
		{
		switch(b)
			{
			case 23: return "chrX";
			case 24: return "chrY";
			case 25: return "chrM";
			default: return "chr"+(int)b;
			}
		}
	
	@Override
	public int compareTo(ChromPosition o)
		{
		int i= (int)(chrom)- (int)(o.chrom);
		if(i!=0) return i;
		i= position-o.position;
		return i;
		}
	
	
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (int)(chrom);
		result = prime * result + position;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ChromPosition other = (ChromPosition) obj;
		return this.compareTo(other)==0;
	}

	public byte getChromosomeId()
		{
		return this.chrom;
		}
	
	public String getChromosome()
		{
		return denormalize(this.chrom);
		}
	
	public int getPosition()
		{
		return position;
		}
	
	@Override
	public String toString()
		{
		return getChromosome()+":"+position;
		}
	
	
	
	
	}
